<template>
  <div>
    <el-form
      ref="formRef"
      :model="formModel"
      label-position="top"
      class="person-form"
    >
      <el-form-item label="人员信息" prop="person">
        <div class="person-list-container">
          <div
            v-for="(personItem, index) in formModel.person"
            :key="index"
            class="person-item"
          >
            <el-row :gutter="20" align="middle">
              <el-col :span="1" class="item-index-col">
                <span class="item-index">{{ index + 1 }}</span>
              </el-col>

              <el-col :span="19">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item
                      label="姓名 (Name)"
                      :prop="'person.' + index + '.name'"
                      :rules="rules.name"
                    >
                      <el-input
                        v-model="personItem.name"
                        placeholder="请输入姓名"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="IP 地址 (IPv4)"
                      :prop="'person.' + index + '.ip'"
                      :rules="rules.ip"
                    >
                      <el-input
                        v-model="personItem.ip"
                        placeholder="例如: 192.168.1.1"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="MAC 地址"
                      :prop="'person.' + index + '.mac'"
                      :rules="rules.mac"
                    >
                      <el-input
                        v-model="personItem.mac"
                        placeholder="例如: 00:1A:2B:3C:4D:5E"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="4" class="action-buttons">
                <el-button
                  v-if="index > 0"
                  type="danger"
                  :icon="Delete"
                  circle
                  @click="removePersonItem(index)"
                />
                <el-button
                  v-if="index === formModel.person.length - 1"
                  type="primary"
                  :icon="Plus"
                  circle
                  @click="addPersonItem"
                />
              </el-col>
            </el-row>

            <el-divider v-if="index < formModel.person.length - 1" />
          </div>
        </div>
      </el-form-item>

      <el-form-item class="form-footer">
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// script 部分与之前完全相同，无需任何修改
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";

interface PersonItem {
  name: string;
  ip: string;
  mac: string;
}

const formRef = ref<FormInstance>();

const formModel = reactive<{ person: PersonItem[] }>({
  person: [{ name: "", ip: "", mac: "" }],
});

const validateIp = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("IP 地址不能为空"));
  }
  const ipv4Regex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  if (!ipv4Regex.test(value)) {
    callback(new Error("请输入有效的 IPv4 地址"));
  } else {
    callback();
  }
};

const validateMac = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("MAC 地址不能为空"));
  }
  const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
  if (!macRegex.test(value)) {
    callback(new Error("请输入有效的 MAC 地址，例如: 00:1A:2B:3C:4D:5E"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  ip: [{ required: true, validator: validateIp, trigger: "blur" }],
  mac: [{ required: true, validator: validateMac, trigger: "blur" }],
});

const addPersonItem = () => {
  formModel.person.push({ name: "", ip: "", mac: "" });
};

const removePersonItem = (index: number) => {
  formModel.person.splice(index, 1);
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("校验成功，提交的数据:", formModel.person);
      ElMessage({ message: "提交成功!", type: "success" });
    } else {
      console.log("校验失败:", fields);
      ElMessage({ message: "表单校验失败，请检查输入项。", type: "error" });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formModel.person = [{ name: "", ip: "", mac: "" }];
  formEl.resetFields();
};
</script>

<style scoped>
/* 外部总容器样式 */
.person-list-container {
  width: 100%;
  padding: 20px 20px 0 20px; /* 增加内边距，底部padding为0，由最后一个条目的margin-bottom撑开 */
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
}

/* 内部每个条目的样式 */
.person-item .el-form-item {
  /* 调整表单项的下边距，使其在条目内更紧凑 */
  margin-bottom: 18px;
}

/* 序号列的样式 */
.item-index-col {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px; /* 确保序号与输入框大致垂直居中 */
}

/* 序号本身的样式 */
.item-index {
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-secondary);
  background-color: var(--el-fill-color-lighter);
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 分割线样式 */
.person-item .el-divider {
  margin: 0 0 20px 0; /* 调整分割线的上下边距 */
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px; /* 按钮之间的间距 */
}

.form-footer {
  margin-top: 20px;
}
</style>
